import Dialog from 'tdesign-miniprogram/dialog/index'
import Toast, { hideToast } from 'tdesign-miniprogram/toast/index'
import { getDateDiff } from "../../../util/util"
const app = getApp()

const dialogConfig = {
  context: this,
  title: '提示',
  content: '确定执行该操作？',
  confirmBtn: '确认',
  cancelBtn: '取消'
};

Page({
  data: {
    theme: 'light',
    user: null,
    loading: false,
    onGlobalUserChange: null,
    flow: null,
    content: '',
    getDateDiff,
    status: {
      10: '已创建',
      20: '已处理',
      30: '完成',
      40: '已拒绝',
    }
  },
  onLoad({id}) {
    if (id) {
      this.getData(id)
    } else {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.on('init', ({value}) => {
        value.post = { ...value.post, ...value.to }
        value.session.forEach(i => i.timeDiff = getDateDiff(i.createdTime))
        this.setData({ flow: value })
      })
    }

    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user
    })
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(user) {
    this.setData({ user })
  },
  back() {
    wx.navigateBack()
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  toastHide() {
    hideToast({
      context: this,
      selector: '#t-toast',
    });
  },
  onContentChange(e) {
    this.setData({
      content: e.detail.value?.substr(0, 499)
    })
  },
  onContentEnter() {
    if (this.data.user) this.submit()
  },
  // onChange(e) {
  //   const value = +e.detail.value
  //   this.setData({
  //     value
  //   })
  //   this.getOpenerEventChannel().emit('change', value)
  //   this.back()
  // },
  getUserInfoOnSubmit(e) {
    this.setData({
      loading: true
    })
    app.registerUser(e.detail.userInfo)
    .then((user) => {
      this.data.user = user
      this.submit()
    })
    .finally(() => {
      this.setData({
        loading: false
      })
    })
  },
  getData(id) {
    wx.cloud.callFunction({
      name: 'flow',
      data: {
        action: 'get',
        data: id,
      }
    })
    .then(res => {
      const f = res.result.data
      f.post = { ...f.post, ...f.to }
      f.session.forEach(i => i.timeDiff = getDateDiff(i.createdTime))
      this.setData({
        flow: f
      })
    })
  },
  submit() {
    wx.requestSubscribeMessage({
      tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
    })
    .finally(() => {
      this.setData({
        loading: true
      })
      const { flow, user, content } = this.data
      wx.cloud.callFunction({
        name: 'flow',
        data: {
          action: 'comment',
          data: {
            _id: flow._id,
            to: user.openid === flow.to.openid ? flow.from.openid : flow.to.openid,
            content,
            openid: user.openid,
            nickName: user.nickName,
            avatarUrl: user.avatarUrl
          }
        },
      })
      .then(res => {
        this.setData({
          content: '',
          flow: {
            ...this.data.flow,
            session: [...this.data.flow.session, {
              content,
              openid: user.openid,
              nickName: user.nickName,
              avatarUrl: user.avatarUrl,
              timeDiff: getDateDiff(new Date())
            }]
          }
        })
        // this.back()
      })
      .finally(() =>{
        this.setData({
          loading: false
        })
      })
    })
   
  },
  onShareAppMessage() {
    return {
      title: '东鸣西应',
      path: 'packageHome/pages/post-detail/index?id=' + this.flow?.post._id
    }
  },
  updateFlow(data) {
    return wx.cloud.callFunction({
      name: 'flow',
      data: {
        action: 'update',
        data
      }
    })
  },
  doFlow() {
    const {flow} = this.data
    dialogConfig.content = '处理对方发起的互动'
    Dialog.confirm(dialogConfig)
    .then(() => {
      this.toast({
        theme: 'loading',
        direction: 'column',
        duration: 10000,
      })
      return this.updateFlow({
        _id: flow._id,
        from: flow.from,
        to: flow.to,
        status: 20
      })
    })
    .then(res => {
      this.setData({
        flow: {...flow, status: 20},
      })
      this.toastHide()
      wx.requestSubscribeMessage({
        tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
      })
    })
    .catch(e =>{
      console.error(e)
      this.toast({
        theme: 'fail',
        direction: 'column',
        message: '操作失败'
      })
    })
  },
  confirmFlow() {
    const { flow } = this.data
    dialogConfig.content = '确定对方的处理结果'
    Dialog.confirm(dialogConfig)
    .then(() => {
      this.toast({
        theme: 'loading',
        direction: 'column',
        duration: 10000,
      })
      return this.updateFlow({
        _id: flow._id,
        from: flow.from,
        to: flow.to,
        status: 30
      })
    })
    .then(res => {
      this.setData({
        flow: {...flow, status: 30},
      })
      this.toastHide()
      wx.requestSubscribeMessage({
        tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
      })
    })
    .catch(e =>{
      console.error(e)
      this.toast({
        theme: 'fail',
        direction: 'column',
        message: '操作失败'
      })
    })
  },
  refuseFlow(e) {
    dialogConfig.content = ''
    Dialog.confirm(dialogConfig)
    .then(() => {
      this.toast({
        theme: 'loading',
        direction: 'column',
        duration: 10000,
      })
      return this.updateFlow({
        _id: e._id,
        from: flow.from,
        to: flow.to,
        status: 40
      })
    })
    .then(res => {
      this.setData({
        flow: {...flow, status: 40},
      })
      this.toastHide()
      wx.requestSubscribeMessage({
        tmplIds: ['AC3OZlKk4-S8m1m_RcqAx4fj5hvZ4jRZj9qAovye-zQ'],
      })
    })
    .catch(e =>{
      console.error(e)
      this.toast({
        theme: 'fail',
        direction: 'column',
        message: '操作失败'
      })
    })
  }
})
